/* SANDBOX BIDGE FUNCTIONS */

var Bridge = {};

function setBridge(){
	var childApp = document.getElementById("application").contentWindow;
	childApp.parentSandboxBridge = Bridge;
}

Bridge.authenticate = function(username, password, username_identica, password_identica){

	if (username && password) {
		dump('username: '+username+ 'password: '+password);
	// DO TWITTER LOGIN	
    	var tok = username + ':' + password;
		var hash = Base64.encode(tok);		
		var auth = "Basic " + hash;
		var request = new air.URLRequest("http://twitter.com/account/verify_credentials");
		var header = new air.URLRequestHeader("Authorization", auth);
		request.method = air.URLRequestMethod.GET;
		request.requestHeaders.push(header);
		air.URLRequestDefaults.userAgent = 'Twitch';
	
		var variables = new air.URLLoader();
		variables.dataFormat = air.URLLoaderDataFormat.TEXT;
		variables.addEventListener(air.IOErrorEvent.IO_ERROR , errorHandler);
		variables.addEventListener(air.Event.COMPLETE, completeLoginHandler);
		
		try
		{
	    	variables.load(request);
		} 
		catch (error)
		{
			var childInterface = document.getElementById("application").contentWindow.childSandboxBridge;
			childInterface.showLoginError('twitter');
		}
	
	}
	
	if (username_identica && password_identica) {
	// DO IDENTI.CA LOGIN	
    	var tok = username_identica + ':' + password_identica;
		var hash = Base64.encode(tok);		
		var auth = "Basic " + hash;
		var request = new air.URLRequest("http://identi.ca/api/account/verify_credentials.xml");
		var header = new air.URLRequestHeader("Authorization", auth);
		request.method = air.URLRequestMethod.GET;
		request.requestHeaders.push(header);
		air.URLRequestDefaults.userAgent = 'Twitch';
	
		var variables = new air.URLLoader();
		variables.dataFormat = air.URLLoaderDataFormat.TEXT;
		variables.addEventListener(air.IOErrorEvent.IO_ERROR , errorHandler_identica);
		variables.addEventListener(air.Event.COMPLETE, completeLoginHandler_identica);
	
		try
		{
	    	variables.load(request);
		} 
		catch (error)
		{
			var childInterface = document.getElementById("application").contentWindow.childSandboxBridge;
			childInterface.showLoginError('identi.ca');
		}
	
	}
	
	function errorHandler(event) {
		var childInterface = document.getElementById("application").contentWindow.childSandboxBridge;
		childInterface.showLoginError('twitter');
	}
	
	function errorHandler_identica(event) {
		dump(event);
		var childInterface = document.getElementById("application").contentWindow.childSandboxBridge;
		childInterface.showLoginError('identi.ca');
	}
	
	function completeLoginHandler(event)
	{ 	
	    var loader = event.target;
		dump('response: ' + loader.data);
		if (loader.data == 'Authorized') {
			var bytes = new air.ByteArray();
			bytes.writeUTFBytes('1');
			air.EncryptedLocalStore.setItem("loggedin_twitter", bytes);
			dropTimelineTable();
			createTimelineTable();	
			document.getElementById('application').src = 'messages.html';
			document.getElementById('bottomBar').style.visibility = 'visible';
			document.getElementById('logout').style.visibility = 'visible';
		} else {
			var childInterface = document.getElementById("application").contentWindow.childSandboxBridge;
			childInterface.showLoginError('twitter');
		}
	}
	
	function completeLoginHandler_identica(event)
	{ 	
	    var loader = event.target;
		air.trace(loader.data);
		if (loader.data == '<authorized>true</authorized>') {
			var bytes = new air.ByteArray();
			bytes.writeUTFBytes('1');
			air.EncryptedLocalStore.setItem("loggedin_identica", bytes);
			dropTimelineTable();
			createTimelineTable();	
			document.getElementById('application').src = 'messages.html';
			document.getElementById('bottomBar').style.visibility = 'visible';
			document.getElementById('logout').style.visibility = 'visible';
		} else {
			var childInterface = document.getElementById("application").contentWindow.childSandboxBridge;
			childInterface.showLoginError('identi.ca');
		}
	}
	
}

Bridge.getUsername = function(){
	var user = '';
    user = air.EncryptedLocalStore.getItem("username");
	return user;
}

Bridge.gotoURL = function(url){
	//var url = event.srcElement.name;
	var urlReq = new air.URLRequest(url);  
	air.navigateToURL(urlReq);
}

Bridge.getPassword = function(){
	var pass = '';
    pass = air.EncryptedLocalStore.getItem("password");
	return pass;
}

Bridge.insertReply = function(username){
	var status = "@"+username+" ";
	document.getElementById('status').value = status;
}

Bridge.trace = function(string){
	dump(string);
}

Bridge.updateFriends = function(string){
//TAE 2008.08.18 (START
//	updateTimelineSQL();
	try {
		//dump('refresh on ' + new Date());
		showStatus('refresh twitter', true);
		updateTimelineSQL();
	} catch(e) {
		dump('update friends twitter: ' + e);
	}	
//TAE 2008.08.18 (END
}

Bridge.updateFriends_identica = function(string){
	try {
		//dump('refresh on ' + new Date());
		showStatus('refresh identi.ca', true);
		updateTimelineSQL_identica();
	} catch(e) {
		dump('update friends identi.ca: ' + e);
	}	
}

Bridge.updateReplies = function(string){
//TAE 2008.08.18 (START
//	updateRepliesTimelineSQL();
	try {
		//dump('updateReplies on ' + new Date());
		showStatus('replies twitter',true);
		updateRepliesTimelineSQL();
	} catch(e) {
		dump('update Replies twitter: ' + e);
	}	
//TAE 2008.08.18 (END
}

Bridge.updateReplies_identica = function(string){
	try {
		//dump('updateReplies on ' + new Date());
		showStatus('replies identi.ca',true);
		updateRepliesTimelineSQL_identica();
	} catch(e) {
		dump('update Replies identi.ca: ' + e);
	}	
}

//TAE 2008.08.17 (start
Bridge.updateDirect = function(string){
//TAE 2008.08.18 (START
//	updateDMTimelineSQL();
	try {
		//dump('updateDirect on ' + new Date());
		showStatus('directs twitter',true);
		updateDMTimelineSQL();
	} catch(e) {
		dump('update DM twitter: ' + e);
	}	
//TAE 2008.08.18 (END    
}

Bridge.updateDirect_identica = function(string){
	try {
		//dump('updateDirect on ' + new Date());
		showStatus('directs identi.ca',true);
		updateDMTimelineSQL_identica();
	} catch(e) {
		dump('update DM identi.ca: ' + e);
	}	 
}

//TAE 2008.08.17 (end
Bridge.getTimeline = function(){
//TAE 2008.08.18 (START
//	var messages = updateTimelineClient();
	var messages = null;
	
	try {
		//dump('get timeline...');
		messages = updateTimelineClient();
	} catch(e) {
		dump('timeline: ' + e);
	}
//TAE 2008.08.18 (END 
	return messages;
}

Bridge.getUsername = function(){
	var username = air.EncryptedLocalStore.getItem("username");
	return username;
}

Bridge.getPassword = function(){
	var password = air.EncryptedLocalStore.getItem("password");
	return password;
}

Bridge.setUsername = function(username){
	var bytes = new air.ByteArray();
	bytes.writeUTFBytes(username);
	air.EncryptedLocalStore.setItem("username", bytes);
}

Bridge.setPassword = function(password){
	var bytes = new air.ByteArray();
	bytes.writeUTFBytes(password);
	air.EncryptedLocalStore.setItem("password", bytes);
}

Bridge.getUsernameIdentica = function(){
	var username_identica = air.EncryptedLocalStore.getItem("username_identica");
	return username_identica;
}

Bridge.getPasswordIdentica = function(){
	var password_identica = air.EncryptedLocalStore.getItem("password_identica");
	return password_identica;
}

Bridge.setUsernameIdentica = function(username_identica){
	var bytes = new air.ByteArray();
	bytes.writeUTFBytes(username_identica);
	air.EncryptedLocalStore.setItem("username_identica", bytes);
}

Bridge.setPasswordIdentica = function(password_identica){
	var bytes = new air.ByteArray();
	bytes.writeUTFBytes(password_identica);
	air.EncryptedLocalStore.setItem("password_identica", bytes);
}

Bridge.loggedInIdentica = function(){
	var loggedin_identica = air.EncryptedLocalStore.getItem("loggedin_identica");
	return loggedin_identica;
}

Bridge.loggedInTwitter = function(){
	var loggedin_twitter = air.EncryptedLocalStore.getItem("loggedin_twitter");
	return loggedin_twitter;
}

function sendNewDirect() {
	var status = document.getElementById('status').value;
	var words = new Array();
	words = status.split(" ");
	var user = words[1];
	var text = '';
	//Put array back together to get text
	for (var i = 2; i < words.length; i++) {
		text = text + " " + words[i];
	}
	
	//TAE 2008.09.06 (start
	//Escape function make Thai characters became shit!
	//text = escape(text);
	//TAE 2008.09.09 (START --> Fixed on Issue#13
	//status = escape(status);
	text = text.replace(/\&/ig,'%26');
	//TAE 2008.09.09 (END --> Fixed on Issue#13
	//TAE 2008.09.06 (end
	
	var username = air.EncryptedLocalStore.getItem("username");
	var password = air.EncryptedLocalStore.getItem("password");
	var tok = username + ':' + password;
	var hash = Base64.encode(tok);		
	var auth = "Basic " + hash; 

	var status = "user="+user+"&text="+text+"&source=twitch";
	air.trace(status);
	var variables = new air.URLVariables(status);
	var request = new air.URLRequest();
	request.url = "http://twitter.com/direct_messages/new.xml";
	air.URLRequestDefaults.userAgent = 'Twitch';
	request.method = air.URLRequestMethod.POST;
	request.data = variables;
	var header = new air.URLRequestHeader("Authorization", auth);
	request.requestHeaders.push(header);
	
	var loader = new air.URLLoader();
	loader.dataFormat = air.URLLoaderDataFormat.XML;
	if (words[0] != "track" && words[0] != "untrack") {
		loader.addEventListener(air.Event.COMPLETE, completeUpdateStatusHandlerDM);
		//TAE 2008.08.20 (start
		loader.addEventListener(air.IOErrorEvent.IO_ERROR, ioErrorHandler);
		//TAE 2008.08.20 (end
	}

	try
	{
	    loader.load(request);
	}
	catch (error)
	{

	}
	
	function completeUpdateStatusHandlerDM(event) {
			var conn = openDB();
			var dataXML = event.target.data;
			var parser = new DOMParser();
			var doc = parser.parseFromString(dataXML,"text/xml");
			for (var i = 0; i < doc.getElementsByTagName('direct_message').length; i++) {
				var exists = '';
				var twitter_id = '';
				var created_at = '';
				var text = '';
				var source = '';
				var real_name = '';
				var in_reply_to = '';
				var screen_name = '';
				var profile_image_url = '';
				twitter_id = doc.getElementsByTagName('direct_message')[i].getElementsByTagName('id')[0].childNodes(0).nodeValue;
				created_at = doc.getElementsByTagName('direct_message')[i].getElementsByTagName('created_at')[0].childNodes(0).nodeValue;
				text = doc.getElementsByTagName('direct_message')[i].getElementsByTagName('text')[0].childNodes(0).nodeValue;
				real_name = doc.getElementsByTagName('direct_message')[i].getElementsByTagName('sender')[0].getElementsByTagName('name')[0].childNodes(0).nodeValue;
				screen_name = doc.getElementsByTagName('direct_message')[i].getElementsByTagName('sender')[0].getElementsByTagName('screen_name')[0].childNodes(0).nodeValue;
				var recipient = doc.getElementsByTagName('direct_message')[i].getElementsByTagName('recipient')[0].getElementsByTagName('screen_name')[0].childNodes(0).nodeValue;
				profile_image_url = doc.getElementsByTagName('direct_message')[i].getElementsByTagName('sender')[0].getElementsByTagName('profile_image_url')[0].childNodes(0).nodeValue;
				
				//TAE 2008.09.06 (start
				//source = "[dm to " + recipient + "]";
				//TAE 2008.09.06 (end
				source = "sent to " + recipient;
				//TAE 2008.08.21 (start
				var t  			 = Date.parse(created_at);
				var created_time = parseInt(t);
				//TAE 2008.08.21 (end
				
				// Find and activate URL's
				var re = new RegExp(/(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/ig);
				var matches = text.match(re);
				if (matches && matches.length) { 
					for (var x = 0; x < matches.length; x++) {
						var url = '<a href=# name="'+matches[x]+'" onclick="return gotolink()">'+matches[x]+'</a>';
						text = text.replace(matches[x], url);
					}
				}
				
				//TAE 2008.08.23 (start
				text = setHashTag(text);
				//TAE 2008.08.23 (End
				
				text = escape(text);
				
				// Find URL's in Source
				var re = new RegExp(/<a[^>]*>/ig);
				var matches = source.match(re);
				if (matches && matches.length) { 
					for (var x = 0; x < matches.length; x++) {
						var re2 = new RegExp(/\"[^\"]*\"/ig);
						var matches2 = matches[x].match(re2);
						if (matches2 && matches2.length) { 
							for (var y = 0; y < matches2.length; y++) {
								var from_link = matches2[y];
							}
						}
						var from_url = '<a href="#" name='+from_link+' onclick="return gotolink()">';
						source = source.replace(matches[x], from_url);
					}
				}
				
				// Insert new info into DB
				// create the SQL statement
				var insertStmt = new air.SQLStatement();
				insertStmt.sqlConnection = conn;

				// define the SQL text
				var sql = 
				    "INSERT OR REPLACE INTO timeline (twitter_id, screen_name, real_name, profile_image_url, created_at, text, source, type, service, in_reply_status_id, created_time) " +    
				    "VALUES ('"+twitter_id+"', '"+screen_name+"', '"+real_name+"', '"+profile_image_url+"', '"+created_at+"', '"+text+"', '"+source+"','sent', 'twitter', 0," + created_time +")";
				
				insertStmt.text = sql;

				try
				{
				    // execute the statement
				    insertStmt.execute();
				}
				catch (error)
				{
				    return;
				}
			}

		document.getElementById('status').value = '';
		document.getElementById('countdown').value = '140';
		return false;

	}
	
}

function updateStatus() {
	var status = document.getElementById('status').value;
	var words = new Array();
	words = status.split(" ");
	if (words[0] == 'd' || words[0] == 'D')
	{
		sendNewDirect();
		return;
	}
	var username = air.EncryptedLocalStore.getItem("username");
	var password = air.EncryptedLocalStore.getItem("password");
	var tok = username + ':' + password;
	var hash = Base64.encode(tok);		
	var auth = "Basic " + hash; 

	//TAE 2008.09.09 (START --> Fixed on Issue#13
	//status = escape(status);
	status = status.replace(/\&/ig,'%26');
	//TAE 2008.09.09 (END --> Fixed on Issue#13
	
	var status = "status="+status+"&source=twitch";
	var variables = new air.URLVariables(status);
	
	dump(status);
	
	var request = new air.URLRequest();
	request.url = "http://twitter.com/statuses/update.xml";
	air.URLRequestDefaults.userAgent = 'Twitch';
	request.method = air.URLRequestMethod.POST;
	request.data = variables;
	var header = new air.URLRequestHeader("Authorization", auth);
	request.requestHeaders.push(header);
	
	var loader = new air.URLLoader();
	loader.dataFormat = air.URLLoaderDataFormat.XML;
	if (words[0] != "track" && words[0] != "untrack") {
		loader.addEventListener(air.Event.COMPLETE, completeUpdateStatusHandler);
		//TAE 2008.08.20 (start
		loader.addEventListener(air.IOErrorEvent.IO_ERROR, ioErrorHandler);
		//TAE 2008.08.20 (end
	}

	try
	{
	    loader.load(request);
	}
	catch (error)
	{

	}
	
	function completeUpdateStatusHandler(event) {
			var conn = openDB();
			var dataXML = event.target.data;
			var parser = new DOMParser();
			var doc = parser.parseFromString(dataXML,"text/xml");
			for (var i = 0; i < doc.getElementsByTagName('status').length; i++) {
				var exists = '';
				var twitter_id = '';
				var created_at = '';
				var text = '';
				var source = '';
				var real_name = '';
				var in_reply_to = '';
				var screen_name = '';
				var profile_image_url = '';
				twitter_id = doc.getElementsByTagName('status')[i].getElementsByTagName('id')[0].childNodes(0).nodeValue;
				created_at = doc.getElementsByTagName('status')[i].getElementsByTagName('created_at')[0].childNodes(0).nodeValue;
				source = doc.getElementsByTagName('status')[i].getElementsByTagName('source')[0].childNodes(0).nodeValue;
				text = doc.getElementsByTagName('status')[i].getElementsByTagName('text')[0].childNodes(0).nodeValue;
				real_name = doc.getElementsByTagName('status')[i].getElementsByTagName('user')[0].getElementsByTagName('name')[0].childNodes(0).nodeValue;
				screen_name = doc.getElementsByTagName('status')[i].getElementsByTagName('user')[0].getElementsByTagName('screen_name')[0].childNodes(0).nodeValue;
				profile_image_url = doc.getElementsByTagName('status')[i].getElementsByTagName('user')[0].getElementsByTagName('profile_image_url')[0].childNodes(0).nodeValue;
				
				//TAE 2008.08.21 (start
				var t  			 = Date.parse(created_at);
				var created_time = parseInt(t);
				//TAE 2008.08.21 (end
				
				// Find and activate URL's
				var re = new RegExp(/(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/ig);
				var matches = text.match(re);
				if (matches && matches.length) { 
					for (var x = 0; x < matches.length; x++) {
						var url = '<a href=# name="'+matches[x]+'" onclick="return gotolink()">'+matches[x]+'</a>';
						text = text.replace(matches[x], url);
					}
				}
				
				//TAE 2008.08.23 (start
				text = setHashTag(text);
				//TAE 2008.08.23 (End
				
				text = escape(text);
				
				// Find URL's in Source
				var re = new RegExp(/<a[^>]*>/ig);
				var matches = source.match(re);
				if (matches && matches.length) { 
					for (var x = 0; x < matches.length; x++) {
						var re2 = new RegExp(/\"[^\"]*\"/ig);
						var matches2 = matches[x].match(re2);
						if (matches2 && matches2.length) { 
							for (var y = 0; y < matches2.length; y++) {
								var from_link = matches2[y];
							}
						}
						var from_url = '<a href="#" name='+from_link+' onclick="return gotolink()">';
						source = source.replace(matches[x], from_url);
					}
				}
				
				// Insert new info into DB
				// create the SQL statement
				var insertStmt = new air.SQLStatement();
				insertStmt.sqlConnection = conn;

				// define the SQL text
				var sql = 
				    "INSERT OR REPLACE INTO timeline (twitter_id, screen_name, real_name, profile_image_url, created_at, text, source, type, service, in_reply_status_id, created_time) " + 
				    "VALUES ('"+twitter_id+"', '"+screen_name+"', '"+real_name+"', '"+profile_image_url+"', '"+created_at+"', '"+text+"', '"+source+"','friend', 'twitter', 0," + created_time +")";
				
				insertStmt.text = sql;

				try
				{
				    // execute the statement
				    insertStmt.execute();
				}
				catch (error)
				{
				    return;
				}
			}

		document.getElementById('status').value = '';
		document.getElementById('countdown').value = '140';
		return false;

	}
	
}

function updateStatus_identica() {
	var status = document.getElementById('status').value;
	var words = new Array();
	words = status.split(" ");
	if (words[0] == 'd' || words[0] == 'D')
	{
		return;
	}
	var username_identica = air.EncryptedLocalStore.getItem("username_identica");
	var password_identica = air.EncryptedLocalStore.getItem("password_identica");
	var tok = username_identica + ':' + password_identica;
	var hash = Base64.encode(tok);		
	var auth = "Basic " + hash; 

	//TAE 2008.09.09 (START --> Fixed on Issue#13
	//status = escape(status);
	status = status.replace(/\&/ig,'%26');
	//TAE 2008.09.09 (END --> Fixed on Issue#13
	
	var status = "status="+status+"&source=twitch";
	var variables = new air.URLVariables(status);
	
	dump(status);
	
	var request = new air.URLRequest();
	request.url = "http://identi.ca/api/statuses/update.xml";
	air.URLRequestDefaults.userAgent = 'Twitch';
	request.method = air.URLRequestMethod.POST;
	request.data = variables;
	var header = new air.URLRequestHeader("Authorization", auth);
	request.requestHeaders.push(header);
	
	var loader = new air.URLLoader();
	loader.dataFormat = air.URLLoaderDataFormat.XML;
	if (words[0] != "track" && words[0] != "untrack") {
		loader.addEventListener(air.Event.COMPLETE, completeUpdateStatusHandler_identica);
		//TAE 2008.08.20 (start
		loader.addEventListener(air.IOErrorEvent.IO_ERROR, ioErrorHandler);
		//TAE 2008.08.20 (end
	}

	try
	{
	    loader.load(request);
	}
	catch (error)
	{

	}
	
	function completeUpdateStatusHandler_identica(event) {
			var conn = openDB();
			var dataXML = event.target.data;
			var parser = new DOMParser();
			var doc = parser.parseFromString(dataXML,"text/xml");
			for (var i = 0; i < doc.getElementsByTagName('status').length; i++) {
				var exists = '';
				var twitter_id = '';
				var created_at = '';
				var text = '';
				var source = '';
				var real_name = '';
				var in_reply_to = '';
				var screen_name = '';
				var profile_image_url = '';
				twitter_id = doc.getElementsByTagName('status')[i].getElementsByTagName('id')[0].childNodes(0).nodeValue;
				created_at = doc.getElementsByTagName('status')[i].getElementsByTagName('created_at')[0].childNodes(0).nodeValue;
				source = doc.getElementsByTagName('status')[i].getElementsByTagName('source')[0].childNodes(0).nodeValue;
				text = doc.getElementsByTagName('status')[i].getElementsByTagName('text')[0].childNodes(0).nodeValue;
				real_name = doc.getElementsByTagName('status')[i].getElementsByTagName('user')[0].getElementsByTagName('name')[0].childNodes(0).nodeValue;
				screen_name = doc.getElementsByTagName('status')[i].getElementsByTagName('user')[0].getElementsByTagName('screen_name')[0].childNodes(0).nodeValue;
				profile_image_url = doc.getElementsByTagName('status')[i].getElementsByTagName('user')[0].getElementsByTagName('profile_image_url')[0].childNodes(0).nodeValue;
				
				//TAE 2008.08.21 (start
				var t  			 = Date.parse(created_at);
				var created_time = parseInt(t);
				//TAE 2008.08.21 (end
				
				// Find and activate URL's
				var re = new RegExp(/(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/ig);
				var matches = text.match(re);
				if (matches && matches.length) { 
					for (var x = 0; x < matches.length; x++) {
						var url = '<a href=# name="'+matches[x]+'" onclick="return gotolink()">'+matches[x]+'</a>';
						text = text.replace(matches[x], url);
					}
				}
				
				//TAE 2008.08.23 (start
				text = setHashTag(text);
				//TAE 2008.08.23 (End
				
				text = escape(text);
				
				// Find URL's in Source
				var re = new RegExp(/<a[^>]*>/ig);
				var matches = source.match(re);
				if (matches && matches.length) { 
					for (var x = 0; x < matches.length; x++) {
						var re2 = new RegExp(/\"[^\"]*\"/ig);
						var matches2 = matches[x].match(re2);
						if (matches2 && matches2.length) { 
							for (var y = 0; y < matches2.length; y++) {
								var from_link = matches2[y];
							}
						}
						var from_url = '<a href="#" name='+from_link+' onclick="return gotolink()">';
						source = source.replace(matches[x], from_url);
					}
				}
				
				// Insert new info into DB
				// create the SQL statement
				var insertStmt = new air.SQLStatement();
				insertStmt.sqlConnection = conn;

				// define the SQL text
				var sql = 
				    "INSERT OR REPLACE INTO timeline (twitter_id, screen_name, real_name, profile_image_url, created_at, text, source, type, service, in_reply_status_id, created_time) " + 
				    "VALUES ('"+twitter_id+"', '"+screen_name+"', '"+real_name+"', '"+profile_image_url+"', '"+created_at+"', '"+text+"', '"+source+"','friend', 'identica', 0," + created_time +")";
				
				insertStmt.text = sql;

				try
				{
				    // execute the statement
				    insertStmt.execute();
				}
				catch (error)
				{
				    return;
				}
			}

		document.getElementById('status').value = '';
		document.getElementById('countdown').value = '140';
		return false;

	}
	
}

function getTinyURL() {
	var txt = document.getElementById('status');
	
	//TAE 2008.08.20 (start
	var sl = (txt.value).substring(txt.selectionStart,txt.selectionEnd);
	if(!sl.length) {
		//no URL selected
		dump('no selected text');
		//Show windows
		showTinyURL();
		return;
	}
	callbackTinyURL(sl);
	//TAE 2008.08.20 (end
}

//TAE 2008.08.17 (start
function dump(msg) {
	air.trace('>>' + msg + '\n');
} 

function setHandleHTTPAuth(state) {
	dump('required HTTPAuth = ' + state);
	if (state) {
		window.htmlLoader.authenticate = true;
	} else {
		window.htmlLoader.authenticate = false;
	}
	
	dump('set HTTPAuth = ' + window.htmlLoader.authenticate);
}
//TAE 2008.08.17 (end

//TAE 2008.08.19 (start
function showStatus(msg, flg) {
	if(flg) {
		var d = new Date();
		var h = d.getHours();
		var m = d.getMinutes();
		
		time = (h < 10 ? "0" : "") + h + ":" +
			   (m < 10 ? "0" : "") + m;
		
		msg  = msg + " at " + time;
	}
	
	document.getElementById('status_msg').innerHTML = msg;
}
//TAE 2008.08.19 (end

//TAE 2008.08.20 (start
function ioErrorHandler(event) {
	dump(event);
	showStatus('Can\'t connect to server', true);
	return;
}

function httpStatus(event) {
	dump(event.status);
	if(event.status == 200) 
	{ 
		return; 
	}	
	else if(event.status == 400) 
	{
		//twitter error...
		dump(event.target.data);
		showStatus('twitter: Maximum Exceed', true);
	}
	else if(event.status == 401) 
	{
		//twitter error...
		dump(event.target.data);
		showStatus('twitter: Not Authorized', true);
	}
	else 
	{
		//twitter error...
		dump(event.target.data);
		showStatus('twitter: Can\'t connect to server', true);
	}

}

function httpStatus_identica(event) {
	dump(event.status);
	if(event.status == 200) 
	{ 
		return; 
	}	
	else if(event.status == 400) 
	{
		//twitter error...
		dump(event.target.data);
		showStatus('identica: Maximum Exceed', true);
	}
	else if(event.status == 401) 
	{
		//twitter error...
		dump(event.target.data);
		showStatus('identica: Not Authorized', true);
	}
	else 
	{
		//twitter error...
		dump(event.target.data);
		showStatus('identica: Can\'t connect to server', true);
	}
	return;
}

Bridge.ioErrorHandler	= function(event) {
	ioErrorHandler(event);
	return;
}

Bridge.httpStatus	= function(event) {
	httpStatus(event);
	return;
}

Bridge.httpStatus_identica	= function(event) {
	httpStatus_identica(event);
	return;
}

Bridge.insertDM = function(username){
	var status = "d "+username+" ";
	document.getElementById('status').value = status;
}

Bridge.gotoURL = function(url){
	//var url = event.srcElement.name;
	var urlReq = new air.URLRequest(url);  
	air.navigateToURL(urlReq);
}

function callbackTinyURL(sl) {
	var requrl = "http://srnk.net/create.php?url="+sl;
	var request = new air.URLRequest(requrl);
	request.method = air.URLRequestMethod.GET;			
	var variables = new air.URLLoader();
	variables.dataFormat = air.URLLoaderDataFormat.TEXT;
	variables.addEventListener(air.Event.COMPLETE, completeTinyURLHandler);
	
	//TAE 2008.08.20 (start
	variables.addEventListener(air.IOErrorEvent.IO_ERROR, ioErrorHandler);
	variables.addEventListener(air.HTTPStatusEvent.HTTP_RESPONSE_STATUS, httpStatus);
	//TAE 2008.08.20 (end
	
	try
	{
	    variables.load(request);
	} 
	catch (error)
	{

	}

	function completeTinyURLHandler(event)
	{ 
	    var tinyurl = event.target.data;
		var status = document.getElementById('status').value;
		var txt = document.getElementById('status');
		var sl = (txt.value).substring(txt.selectionStart,txt.selectionEnd);
	    status = status.replace(sl, tinyurl);
		document.getElementById('status').value = status;
	}
}
//TAE 2008.08.20 (end

//TAE 2008.08.22 (start
function showTinyURL() {
	// check the clipboard first
	var http = /^http\:\/\//;
	var s = '';
	var sel = window.getSelection();	
	var clippy = air.Clipboard.generalClipboard.getData(air.ClipboardFormats.TEXT_FORMAT, air.ClipboardTransferMode.CLONE_ONLY);
			
	s = http.test(sel.toString()) ? sel.toString() : (http.test(clippy) ? clippy : '');

	document.getElementById('snurlurl').value = s;
	document.getElementById('snurlui').style.display = 'block';
	document.getElementById('snurlurl').focus();
}
//TAE 2008.08.22 (end

//TAE 2008.08.23 (start
function showUploadPic() {
	document.getElementById('picui').style.display = 'block';
	
	//Tae 2008.08.26 (Start
	init_post_pic();
	//Tae 2008.08.26 (End
}

function hiddenUploadPic() {
	document.getElementById('picui').style.display = 'none';
	document.getElementById('status').focus();
	
	//Tae 2008.08.26 (Start
	destroy_post_pic();
	//Tae 2008.08.26 (End
}
//TAE 2008.08.23 (end



//TAE 2008.09.06 (Start
Bridge.setToolTips = function()
{
	/* setup tooltips */
	var as = [];

	$$('a').each(function(a){
		if (a.getAttribute('title')) as.push(a);
	});

	new Tips(as, {maxOpacity: 0.9, maxTitleChars: 25});
}
//TAE 2008.09.06 (End